package digital.store.springmvc.controller;


import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;


import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import digital.store.springmvc.service.CategoryService;
import digital.store.springmvc.service.ProductService;
import digital.store.tutorial.springmvc.model.Product;



@Controller
@RequestMapping(value = "/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    
    @Autowired
    private CategoryService categorySerive;
    /**
     * Show book list
     * @param model
     * @return
     */
   
	private String uploadFolderPath;
	ServletConfig config;

	public String getUploadFolderPath() {
		return uploadFolderPath;
	}

	public void setUploadFolderPath(String uploadFolderPath) {
		this.uploadFolderPath = uploadFolderPath;
	}
	
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model) {
        Collection<Product> products = productService.findAll();
  
        model.addAttribute("products", products);
        
       return "admin/product/list-p";
    }

    /**
     * Show create form
     * @param model
     * @return
     */
    
  
  
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String showCreateForm(Model model) {
    	
        model.addAttribute(new Product());
        model.addAttribute("listcategory", categorySerive.findAll());
        return "admin/product/create-edit-p";
    }

    /**
     * Show edit form
     * @param model
     * @return
     */
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public String showEditForm(@PathVariable Long id, Model model) {
        Product product = productService.findById(id);
        model.addAttribute(product);
        return "admin/product/create-edit-p";
    }

    /**
     * Create a new product or update an existing product
     * @param model
     * @return
     */
    @RequestMapping(value="save", method = RequestMethod.POST)
    public String save(Product product, BindingResult result,HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
        if (result.hasErrors()) {
            return "admin/product/create-edit-p";
        }
        System.err.println("-------------------------------------------");
		try {
			MultipartFile file = product.getImgData1();
			String fileName = null;
			InputStream inputStream = null;
			OutputStream outputStream = null;
			if (file.getSize() > 0) {
				inputStream = file.getInputStream();
				if (file.getSize() > 100000) {
					System.out.println("File Size:::" + file.getSize());
					return "/product";
				}
				System.out.println("size::" + file.getSize());
				fileName = request.getSession().getServletContext().getRealPath("") + "/images/" + file.getOriginalFilename();
				
				outputStream = new FileOutputStream(fileName);
				 
				System.out.println("fileName:" + file.getOriginalFilename());

				int readBytes = 0;
				byte[] buffer = new byte[100000];
				while ((readBytes = inputStream.read(buffer, 0, 100000)) != -1) {
					outputStream.write(buffer, 0, readBytes);
				}
				outputStream.flush();
				outputStream.close();
				inputStream.close();
				product.setImg1(file.getOriginalFilename());
			}

			// ..........................................		

		} catch (Exception e) {
			e.printStackTrace();
		}
		product.setStatus("Avaible");
        productService.saveOrUpdate(product);
        return "redirect:/product/";
    }
    
    /**
     * Delete selected products
     * @return
     */
    @RequestMapping(value="delete", method = RequestMethod.POST)
    public String delete(@RequestParam Long[] id) {
        for (int i = 0; i < id.length; i++) {
            productService.delete(id[i]);
        }
        
        return "redirect:/product/";
    }

}
